use std::path::Path;
pub fn image_compress(
    image_path: Box<&Path>,
    out_path: Box<&Path>,
    quality: i32,
) -> Result<(), std::io::Error> {
    let image_data = std::fs::read(*image_path).expect("读取文件失败");

    let exte = image_path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_lowercase());
    let image: image::RgbImage =
        if exte == Some("jpg".to_string()) || exte == Some("jpeg".to_string()) {
            turbojpeg::decompress_image(&image_data).unwrap()
        } else {
            image::load_from_memory(&image_data).unwrap().to_rgb8()
        };

    let jpeg_data = turbojpeg::compress_image(&image, quality, turbojpeg::Subsamp::Sub2x1)
        .expect("JPEG 压缩失败");

    std::fs::write(out_path.as_ref(), jpeg_data).expect("写入文件失败");

    Ok(())
}

pub fn is_image(path: &Path) -> bool {
    if let Some(extension) = path.extension() {
        match extension.to_string_lossy().to_lowercase().as_str() {
            "jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "tiff" => true,
            _ => false,
        }
    } else {
        false
    }
}

#[cfg(test)]
mod image_compress_test {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_image_compress_turbojpeg() {
        let image_path = Path::new("D:\\Pictures\\2.jpg");
        let file_name = image_path.file_stem().unwrap();
        let folder_name = image_path.parent().unwrap();
        let out_path = Path::join(folder_name, format!("{}_compress.jpeg", &file_name)).as_path();
        image_compress(Box::new(image_path), Box::new(out_path), 30).unwrap();
    }
}
